<template>
    <el-dialog
        v-model="dialogVisible"
        title="权限配置"
        width="600px"
        @close="handleClose"
    >
        <el-tree
            ref="treeRef"
            :data="treeData"
            show-checkbox
            node-key="uUID"
            :default-checked-keys="checkedKeys"
            :default-expanded-keys="expandedKeys"
            :check-strictly="true"
            :props="{
                label: 'permissionName',
                children: 'children'
            }"
            @check="handleCheck"
        />
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="handleClose">取消</el-button>
                <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
                    确定
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import type { TreeInstance } from 'element-plus'
import type { UserPermission } from '@/apis/permission'

const props = defineProps<{
    modelValue: boolean
    permissionList: UserPermission[]
    checkedPermissions?: string
}>()

const emit = defineEmits<{
    (e: 'update:modelValue', value: boolean): void
    (e: 'change', value: string): void
}>()

// 状态变量
const dialogVisible = ref(props.modelValue)
const submitLoading = ref(false)
const treeRef = ref<TreeInstance>()
const checkedKeys = ref<string[]>([])
const expandedKeys = ref<string[]>([])
const currentCheckedKeys = ref<string[]>([])

// 监听对话框显示状态
watch(() => props.modelValue, (val) => {
    dialogVisible.value = val
    if (val) {
        // 对话框打开时，重置选中状态
        const permissions = props.checkedPermissions?.split(',') || []
        checkedKeys.value = permissions
        currentCheckedKeys.value = permissions
        // 展开所有父节点
        expandedKeys.value = props.permissionList
            .filter(item => item.parentUUID === '')
            .map(item => item.uUID!)
    }
})

watch(() => dialogVisible.value, (val) => {
    emit('update:modelValue', val)
})

// 转换为树状结构
const treeData = computed(() => {
    const list = [...props.permissionList]
    const map = new Map<string, UserPermission & { children?: UserPermission[] }>()
    const tree: (UserPermission & { children?: UserPermission[] })[] = []

    // 创建映射
    list.forEach(item => {
        map.set(item.uUID!, { ...item })
    })

    // 构建树
    list.forEach(item => {
        const node = map.get(item.uUID!)!
        if (item.parentUUID) {
            const parent = map.get(item.parentUUID)
            if (parent) {
                parent.children = parent.children || []
                parent.children.push(node)
            } else {
                tree.push(node)
            }
        } else {
            tree.push(node)
        }
    })

    return tree
})

// 处理节点选中状态变化
const handleCheck = (node: any, state: { checkedKeys: string[] }) => {
    currentCheckedKeys.value = state.checkedKeys
}

// 提交选择
const handleSubmit = () => {
    if (!treeRef.value) return
    
    submitLoading.value = true
    try {
        emit('change', currentCheckedKeys.value.join(','))
        handleClose()
    } finally {
        submitLoading.value = false
    }
}

// 关闭对话框
const handleClose = () => {
    dialogVisible.value = false
}
</script>

<style scoped lang="scss">
.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 8px;
    margin-top: 16px;
}
</style> 